package cn.itcast.service;

import cn.itcast.dao.UserDao;

import cn.itcast.feign.UserFeignClient;
import cn.itcast.pojo.User;

import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;

import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {
    /*  @Autowired
      private UserDao userDao;*/
    /*public List<User> queryUserById(List<Long> ids) {
        List<User> userList = new ArrayList<>();
        for (Long id : ids) {
            User user = userDao.queryUserById(id);
            userList.add(user);
        }
        return userList;
    }*/
   /* @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;//Eureka客户端.可以获取服务实例信息.*/

   /* public List<User> queryUserById(List<Long> ids) {

        List<User> userList = new ArrayList<>();
        //根据服务名称,获取服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //因为只有一个服务,所以直接获取服务实例对象
        ServiceInstance instance = instances.get(0);
        //  System.out.println("instance = " + instance.toString());
        //获取IP和端口信息
        //String baseUrl = "http://" + instance.getHost() + ":" + instance.getPort() + "/user/";//和配置文件里127.0.0.1共存
        String baseUrl = "http://user-service/user/";//测试熔断机制
        ids.forEach(id -> {
            userList.add(restTemplate.getForObject(baseUrl + id, User.class));
         *//*  //测试多次查询,每隔500毫秒
           try {
               Thread.sleep(500);
           } catch (InterruptedException e) {
               e.printStackTrace();
           }*//*
        });
        return userList;
    }*/

    @Autowired
    private UserFeignClient userFeignClient;

    public List<User> queryUserById(List<Long> ids) {

        List<User> userList = new ArrayList<>();

        ids.forEach(id -> {
            userList.add(userFeignClient.queryUserById(id));//调用feign接口，底层动态代理jdk，
        });
        return userList;
    }
}
